<?php

/**
 * @author dungdhs@gmail.com
 * @copyright 2012
 */
 
function system_dir_scan($dir){
  $aResult = array();
  
  $aFile = glob($dir);
  foreach ($aFile as $file){
  	$aResult[] = array_pop(explode('/', $file));
  }
  
  return $aResult;
}

function system_permission(){
  global $database;
  static $aPerm = null;
  
  if (is_null($aPerm)){
  $aPerm = array();
  
  $res = $database->db_query("SELECT * FROM permissions ORDER BY permission_module ASC");
  while ($perm = $database->db_fetch_assoc($res))
    $aPerm[$perm['permission_id']] = $perm;
  }
  
  return $aPerm;
}

function system_role($role_id=0, $field=''){
  global $database;
  static $aRole = null;
  
  if (is_null($aRole)){
  $aRole = array();
  
  $res = $database->db_query("SELECT * FROM roles ORDER BY role_id ASC");
  while ($role = $database->db_fetch_assoc($res))
    $aRole[$role['role_id']] = $role;
  }
  
  if (!empty($field)){
    $aReturn = array();
    foreach ($aRole as $id=>$role)
    if (isset($role[$field])) 
      $aReturn[$id] = $role[$field];
    return $aReturn;
  }
  
  return $aRole;
}

function system_role_permission(){
  global $database;
  static $aRolePermission = null;
  
  if (is_null($aRolePermission)){
  $aRolePermission = array();
  
  $res = $database->db_query("SELECT * FROM role_permissions ORDER BY rp_role_id ASC");
  while ($role = $database->db_fetch_assoc($res))
    $aRolePermission[$role['rp_role_id']][$role['rp_module']][$role['rp_permission']] = 1;
  }
  
  
  return $aRolePermission;
}

function system_task_load(){
  global $database, $dzTask;
  
  $dzTask = array();
  $res = $database->db_query('SELECT * FROM tasks ORDER BY task_id ASC');
  while ($row = $database->db_fetch_assoc($res)){
  	$dzTask[$row['task_module'].'/'.$row['task_name']] = $row;
  }
}

function system_task_insert($module_name, $task){
  global $database, $dzTask;
  if (!isset($dzTask[$module_name.'/'.$task])){
    $task['title'] = isset($task['title'])?$task['title']:"";
    
    $dzTask[$module_name.'/'.$task['name']] = array(
      'task_id'   => $database->db_insert_id(),
      'task_module' => $module_name,
      'task_name'   => $task['name'],
      'task_perm'   => $task['perm'],
      'task_func'   => $task['func'],
      'task_title'   => $task['title']
    );
    
    if (isset($task['alias'])) url_set_alias($module_name.'/'.$task['name'], $task['alias']);
    
    if (is_string($task['perm'])) $task['perm'] = array($task['perm']);
    
    foreach ($task['perm'] as $term){
      $database->db_query("INSERT INTO permissions(permission_name, permission_module) VALUES ('%s', '%s')", $term, $module_name);
    }
  }
}

function system_module_insert($module_name){
  global $database, $dzModule;
  
  if (!isset($dzModule[$module_name])){
  $database->db_query("INSERT INTO modules(module_name, module_file) VALUES ('%s', '%s')", $module_name, $module_name.'/'.$module_name.'.php');
  $dzModule[$module_name] = array(
    'module_id'   => $database->db_insert_id(),
    'module_file' => $module_name,
    'module_id'   => 1
  );
  }
}

function system_module_load(){
  global $database, $dzModule;
  
  $res = $database->db_query('SELECT * FROM modules ORDER BY module_id ASC');
  while ($row = $database->db_fetch_assoc($res)){
  	$dzModule[$row['module_name']] = $row;
  }
}

function system_module_scan(){
	
  $aModule = system_dir_scan(MODULE_PATH.'*');
  
  foreach ($aModule as $module_name){
  	$modulePath = MODULE_PATH.$module_name.'/'.$module_name.'.php';
  	if (!file_exists($modulePath)) continue;
  	
    system_module_insert($module_name);
    
    // Load module definition
    require_once($modulePath);
    if (function_exists($module_name.'_task')){
      $aTask = call_user_func($module_name.'_task');
      foreach ($aTask as $task_name=>$task){
        $task['name'] = $task_name;
        system_task_insert($module_name, $task);
      }
    }
  }
}

function system_module_func($func){
  global $dzModule;
  
  foreach ($dzModule as $module_name=>$module)
	  if (function_exists($module_name.'_'.$func)){
	  $aTask = call_user_func($module_name.'_'.$func);
  }
}

function system_init(){
  global $dzModule;
  
  theme_js('include/js/dz.js');
  
  system_module_load();
  system_task_load();
  url_load();
  
  system_module_scan();
  
  system_module_func('init');
}

function system_process_page(){
  global $smarty, $user, $session, $fbConfig;
  
  $smarty->assign('ocUser', $user->user_info);
  $smarty->assign('page_content', url_execute());  
  
	system_module_func('process_page');
	  
  $smarty->assign('page_title', theme_title());
  $smarty->assign('page_body_class', theme_body_class());
  $smarty->assign('themeJs', theme_js());
  $smarty->assign('themeCss', theme_css());
  
  $smarty->assign('ocUser', $user->user_info);
  $smarty->assign('loggedin', $user->user_exists);
  $smarty->assign('metaOGP', __ogp_html());
  $smarty->assign('page_description', __ogp_get('og:description'));
  
  PGTheme::message_html();
  $smarty->assign('dzBreadcrumb', theme_breadcrumb());
  
	$smarty->assign('aCat', __category_load('news', true));
	$smarty->assign('userCat', $user->userCatId());
	$smarty->assign('fbConfig', $fbConfig);
  
  $page = arg(0);
  $pref = argurl(0);
  $smarty->assign('pageRef', $page);
  
  if (!empty(PGTheme::$pageTemplate) && $smarty->template_exists("page_".PGTheme::$pageTemplate.".tpl")) $smarty->display("page_".PGTheme::$pageTemplate.".tpl");   
  elseif (is_front() && $smarty->template_exists("page-front.tpl"))  $smarty->display("page-front.tpl");
  elseif ($smarty->template_exists("page_$pref.tpl")) $smarty->display("page_$pref.tpl");
  elseif ($smarty->template_exists("page_$page.tpl")) $smarty->display("page_$page.tpl");
  else $smarty->display("page.tpl");
}

function system_notfound(){
  cheader('<front>');
}

function system_access_denied(){
	global $user, $session;
	if ($user->user_exists){
		PGTheme::set_error('Bạn không có quyền truy cập trang này!');
		cheader('<front>');
	}else{
		$session->set('user_redirect', $_SERVER['REQUEST_URI']);
		cheader('user/login');
	}
}

function system_json($data){
  echo json_encode($data); exit();
}

function system_path($type, $isAbsolute=false){
  switch ($type){
	  case 'theme':
	    return $isAbsolute?PG_ROOT.'templates/v2/':'templates/v2/';
	    break;
	  case 'library':
	  	return $isAbsolute?PG_ROOT.'libs/':'libs/';
	    break;
    case 'modules':
	  	return $isAbsolute?PG_ROOT.'modules/':'modules/';
	    break;
  }
  
  return false;
}

function system_check_hash($hash){
  global $session;
  return true;
  return ($hash==$session->id());
}

function system_query($database_query){
  $args = func_get_args();
  array_shift($args);
  if (isset($args[0]) and is_array($args[0])) { // 'All arguments in one array' syntax
    $args = $args[0];
  }
  
  if (count($args)>0){
    system_query_callback($args, TRUE);
    $database_query = preg_replace_callback('/(%d|%s|%%|%f|%n)/', 'system_query_callback', $database_query);
  }
  
  return $database_query;
}

function system_query_callback($match, $init = FALSE) {
  static $args = NULL;
  
  if ($init) {
    $args = $match;
    return;
  }

  switch ($match[1]) {
    case '%d': // We must use type casting to int to convert FALSE/NULL/(TRUE?)
      $value = array_shift($args);
      // Do we need special bigint handling?
      if ($value > PHP_INT_MAX) {
        $precision = ini_get('precision');
        @ini_set('precision', 16);
        $value = sprintf('%.0f', $value);
        @ini_set('precision', $precision);
      }else {
        $value = (int) $value;
      }
      // We don't need db_escape_string as numbers are db-safe.
      return $value;
    case '%s':
      return mysql_real_escape_string(array_shift($args));
    case '%n':
      // Numeric values have arbitrary precision, so can't be treated as float.
      // is_numeric() allows hex values (0xFF), but they are not valid.
      $value = trim(array_shift($args));
      return is_numeric($value) && !preg_match('/x/i', $value) ? $value : '0';
    case '%%':
      return '%';
    case '%f':
      return (float) array_shift($args);
  }
}

?>